<template>
  <div
    :class="className"
    :style="{height: height, width: width}"
  />
</template>

<script lang="ts">
import * as echarts from 'echarts'
import { BarSeriesOption, EChartsOption } from 'echarts'
import { Component, Prop } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import ResizeMixin from '@/components/Charts/mixins/resize'

@Component({
  name: 'FeedbackChart',
  components: {}
})
export default class extends mixins(ResizeMixin) {
  @Prop({ default: 'chart' }) private className!: string
  @Prop({ default: '100%' }) private width!: string
  @Prop({ default: '200px' }) private height!: string

  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  }

  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  }

  private async initChart() {
    this.chart = echarts.init(this.$el as HTMLDivElement)

    const data = [{
      name: '已反馈',
      value: 125
    }, {
      name: '未反馈',
      value: 231
    }, {
      name: '超期30天内未反馈',
      value: 67
    }, {
      name: '超期60天内未反馈',
      value: 54
    }, {
      name: '超期90天内未反馈',
      value: 71
    }, {
      name: '超期90天以上未反馈',
      value: 23
    }]

    this.setOptions(data)
  }

  private setOptions(data: any[]) {
    if (!this.chart) {
      return
    }

    const row: any = {}
    for (const {
      name,
      value
    } of data) {
      row[name] = value
    }

    const dimensions = ['value',
      '已反馈', '未反馈', '超期30天内未反馈',
      '超期60天内未反馈', '超期90天内未反馈', '超期90天以上未反馈']

    const legendData = [...dimensions].splice(1, 3)

    const series: BarSeriesOption[] = data.map((item, i) => {
      return {
        type: 'bar',
        name: dimensions[i + 1],
        stack: 'A',
        label: { show: true },
        emphasis: { focus: 'series' },
        encode: {
          x: i + 1,
          y: 0
        }
      }
    })

    const color = []
    for (let i = 9; i > 0; i--) {
      color.push(`rgba(0, 112, 192, 0.${i})`)
    }

    const option: EChartsOption = {
      color,
      legend: {
        bottom: 0,
        data: legendData
      },
      tooltip: {},
      barWidth: 60,
      dataset: {
        dimensions,
        source: [row]
      },
      xAxis: { show: false },
      yAxis: {
        type: 'category',
        show: false
      },
      series
    }

    console.log(JSON.stringify(option, null, 2))

    this.chart.setOption(option)
  }
}
</script>

<style lang="scss" scoped>

</style>
